<template>
  <div class="app-container">
    <el-row :gutter="20" class="c-flex c-hidden">
      <!--题库分类数据-->
      <el-col :span="6" :xs="24"  class="c-flex c-height c-dis-flex-col ">
        <div class="head-container">
          <el-input
            v-model="categoryName"
            placeholder="请输入题库分类名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container c-flex c-scroll-y">
          <el-tree
            :data="categoryOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="treeCategory"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--题目数据-->
      <el-col :span="18" :xs="24"  class="c-flex c-height c-dis-flex-col c-hidden">
        <!--   分类下题型数量汇总     -->
        <el-form :model="totalParam" ref="totalParam" :inline="true" label-width="95px" size="small">
          <el-form-item label="单选题：">
            <span>{{totalParam.singleChoice || 0}} 个</span>
          </el-form-item>
          <el-form-item label="多选题：">
            <span>{{totalParam.multipleChoice || 0}} 个</span>
          </el-form-item>
          <el-form-item label="判断题：">
            <span>{{totalParam.trueFalse || 0}} 个</span>
          </el-form-item>
          <el-form-item label="简答题：">
            <span>{{totalParam.shortAnswer || 0}} 个</span>
          </el-form-item>
        </el-form>

        <el-form :model="queryParam" ref="queryForm" :inline="true" label-width="82px" size="small">
          <el-form-item label="题干：">
            <el-input v-model="queryParam.content" clearable></el-input>
          </el-form-item>
          <el-form-item label="知识点标签" clearable>
            <treeselect style="width:205px"  no-options-text="无" v-model="queryParam.subjectId"
                        :options="labelOptions" :show-count="true" placeholder="请选择知识点标签" />
          </el-form-item>
          <el-form-item label="题型：">
            <el-select v-model="queryParam.questionType" clearable>
              <el-option v-for="dict in dict.type.question_type" :key="dict.value" :value="dict.value" :label="dict.label"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="submitForm">查询</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" @click="editQuestion(1,'')" size="mini" v-hasPermi="['practice:exam:question:edit']">单选题创编</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" @click="editQuestion(2,'')" size="mini" v-hasPermi="['practice:exam:question:edit']">多选题创编</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" @click="editQuestion(3,'')" size="mini" v-hasPermi="['practice:exam:question:edit']">判断题创编</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" @click="editQuestion(5,'')" size="mini" v-hasPermi="['practice:exam:question:edit']">简答题创编</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-upload2" @click="handleImport" size="mini" v-hasPermi="['practice:exam:question:import']">导入</el-button>
          </el-col>
        </el-row>
        <el-table v-loading="listLoading" :data="tableData" border fit highlight-current-row style="width: 100%" :header-cell-style="{ textAlign: 'center' }">
          <el-table-column prop="id" label="Id" width="90px" v-if="false"/>
          <el-table-column type="index" width="60px"  label="序号" align="center">
              <template slot-scope="scope">
                <span>{{scope.$index+(queryParam.pageNum - 1) * queryParam.pageSize + 1}}</span>
              </template>
            </el-table-column>
          <el-table-column prop="subjectIdName" label="知识点标签" width="120px"/>
          <el-table-column prop="questionType" label="题型" width="80px" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.question_type" :value="scope.row.questionType"/>
            </template>
          </el-table-column>
          <el-table-column prop="shortTitle" label="题干" show-overflow-tooltip/>
          <el-table-column prop="score" label="分数"  align="center" width="60px" />
          <el-table-column prop="difficult" label="难度"  align="center" width="60px" />
          <el-table-column prop="createTime" label="创建时间" width="160px" />
          <el-table-column label="操作" align="center" width="220px">
            <template slot-scope="{ row }">
              <el-button size="mini" @click="showQuestion(row)">预览</el-button>
              <el-button size="mini" @click="editQuestion(row.questionType,row.id)" v-hasPermi="['practice:exam:question:edit']">编辑</el-button>
              <el-button size="mini" type="danger" @click="deleteQuestion(row)" class="link-left" v-hasPermi="['practice:exam:question:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="queryParam.pageNum" :limit.sync="queryParam.pageSize" @pagination="search"/>
      </el-col>
    </el-row>

    <!--预览-->
    <el-dialog  title="题干预览" :visible.sync="questionShow.dialog" style="width: 100%; height: 100%">
      <QuestionShow :qType="questionShow.qType" :question="questionShow.question" :qLoading="questionShow.loading"/>
    </el-dialog>

    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的数据-->
          <!--          </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import Pagination from "@/components/Pagination";
import QuestionShow from "./components/Show";
import { QuePageList,QueSelect,QueDeleteQuestion,QueTotalQuestion} from "@/api/question";
import {categoryTreeSelect} from "@/api/questionbank/category";
import {knownLedgeLabelTreeSelect} from "@/api/questionbank/knowledgeLabel";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {PaperDeletePaper} from "@/api/examPaper";

export default {
  components: { Pagination, QuestionShow, Treeselect },
  dicts: ['question_type'],
  data() {
    return {
      queryParam: {
        id: null,
        questionType: null,
        level: null,
        subjectId: null,
        categoryIds:null,
        pageNum: 1,
        pageSize: 10,
      },
      totalParam: {
        singleChoice: null,
        multipleChoice: null,
        trueFalse: null,
        gapFilling: null,
        shortAnswer: null
      },
      // 题库分类选项
      categoryOptions: undefined,
      // 知识点标签选项
      labelOptions: undefined,
      listLoading: true,
      tableData: [],
      total: 0,
      questionShow: {
        qType: 0,
        dialog: false,
        question: null,
        loading: false,
      },
      questionType:[
        {key: 1, value: "单选题"},
        {key: 2, value: "多选题"},
        {key: 3, value: "判断题"},
        {key: 4, value: "填空题"},
        {key: 5, value: "简答题"},
      ],
      // 单词导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/api/admin/question/importData"
      },
      //题库分类树选项
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 题库分类名称
      categoryName: undefined,
    };
  },
  watch: {
    // 根据名称筛选题库分类树
    categoryName(val) {
      this.$refs.treeCategory.filter(val);
    }
  },
  created() {
    //查询题库分类树
    this.getCategoryTree();
    //查询知识点标签
    this.getKnownledgeLabelTree();
    //按照题库分类查询各题型数量
    this.getTotalQuestion();
    this.queryParam.pageNum = 1;
    this.search();
  },
  methods: {
    submitForm() {
      this.queryParam.pageNum = 1;
      this.search();
    },
    search() {
      this.listLoading = true;
      QuePageList(this.queryParam).then((data) => {
        this.tableData = data.rows;
        this.total = data.total;
        this.listLoading = false;
      }).catch(()=>{
        this.listLoading = false;
      });
    },
    getTotalQuestion() {
      QueTotalQuestion(this.queryParam).then((res) => {
        this.totalParam = res.data;
      }).catch(()=>{

      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParam.pageNum = 1;
      this.search();
    },
    addQuestion() {
      this.$router.push("/exam/question/edit/singleChoice");
    },
    showQuestion(row) {
      let _this = this;
      this.questionShow.dialog = true;
      this.questionShow.loading = true;
      QueSelect(row.id).then((re) => {
        _this.questionShow.qType = re.data.questionType;
        _this.questionShow.question = re.data;
        _this.questionShow.loading = false;
      });
    },
    editQuestion(questionType,id) {
      let url = '';
      if(questionType===1){
        url = '/practice/question/edit/singleChoice';
      }else if(questionType===2){
        url = '/practice/question/edit/multipleChoice';
      }else if(questionType===3){
        url = '/practice/question/edit/trueFalse';
      }else if(questionType===4){
        url = '/practice/question/edit/gapFilling';
      }else if(questionType===5){
        url = '/practice/question/edit/shortAnswer';
      }
      this.$router.push({ path: url, query: { id: id } });
    },
    deleteQuestion(row) {
      let _this = this;
      _this.$modal.confirm('是否确认删除"' + row.shortTitle+ '"的数据项？').then(function() {
        return QueDeleteQuestion([row.id]);
      }).then(() => {
        _this.search();
        _this.$modal.msgSuccess("删除成功");
      }).catch(() => {
        _this.$modal.msg('已取消删除');
      });
    },
    /** 查询题库分类树结构 */
    getCategoryTree() {
      categoryTreeSelect().then((response) => {
        this.categoryOptions = response.data;
      });
    },
    /** 查询知识库标签树结构 */
    getKnownledgeLabelTree() {
      knownLedgeLabelTreeSelect().then(response => {
        this.labelOptions = response.data;
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      let idsArr = [];
      idsArr.push(data.id);
      const list = data.children;
      let getIdFun = (list)=>{
        if(list){
          list.forEach((item) => {
            idsArr.push(item.id)
            if(item.children){
              item.children.forEach((e) => {
                idsArr.push(e.id)
                getIdFun(e.children);
              });
            }
          });
        }
      }
      getIdFun(list);
      this.queryParam.categoryIds = idsArr.join(",");
      this.queryParam.pageNum = 1;
      //按照题库分类查询各题型数量
      this.getTotalQuestion();
      this.search();
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "题目信息导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('api/admin/question/importTemplate', {
      }, `题目导入模版_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.search();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  },
  computed: {

  },
};
</script>
